from django import http
from django.shortcuts import render
from django.views import View
from django.core.cache import cache

from areas.models import Area
from meiduo_mall.utils.login import MyloginRequiredMiXinView
# Create your views here.
from meiduo_mall.utils.response_code import RET


class AreaView(View):
    def get(self, request):
        area_id = request.GET.get("area_id")

        if area_id:
            area = Area.objects.get(id=area_id)

            sub_data = cache.get("sub_data_%s" % area_id)

            if sub_data:
                context = {
                    "code": RET.OK,
                    "errmsg": "ok",
                    "sub_data": sub_data
                }
                return http.JsonResponse(context)


            sub_data = area.subs.all()

            sub_data_list = []
            for sub in sub_data:
                sub_dict = {"id": sub.id, "name": sub.name}
                sub_data_list.append(sub_dict)

            context = {"code": RET.OK,
                       "errmsg": "ok",
                       "sub_data": {
                           "id": area_id, "name": area.name, "subs": sub_data_list
                       }}

            cache.set("sub_data_%s" % area_id, context["sub_data"], 3600 * 24 * 2)

            return http.JsonResponse(context)

        else:
            areas_list = cache.get("province_list")

            if areas_list:
                context = {"code": RET.OK, "errmsg": "OK", "province_list": areas_list}
                return http.JsonResponse(context)


            areas = Area.objects.filter(parent__isnull=True).all()

            areas_list = []
            for area in areas:
                area_dict = {"id": area.id, "name": area.name}
                areas_list.append(area_dict)

            context = {"code": RET.OK, "errmsg": "OK", "province_list": areas_list}

            cache.set("province_list", areas_list, 60*60*24*2)


            return http.JsonResponse(context)





